import os
from typing import Dict, Any
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

class Config:
    """配置管理类"""

    GPU_CLIENT_CONFIG = {
        'address': os.getenv('GPU_CLIENT_ADDRESS', '192.168.180.158'),
        # 'address': os.getenv('GPU_CLIENT_ADDRESS', '127.0.0.1'),  # 修改为本地地址
        'protocol': os.getenv('GPU_CLIENT_PROTOCOL', 'http'),
        'port': os.getenv('GPU_CLIENT_PORT', '18005')  # 添加端口配置
    }
    
    # 基础配置
    DEBUG = os.getenv('DEBUG', 'False').lower() == 'true'
    SECRET_KEY = os.getenv('SECRET_KEY', 'your-secret-key')
    
    # 文件处理配置
    INPUT_DIR = os.getenv('INPUT_DIR', './pdf_files')
    OUTPUT_DIR = os.getenv('OUTPUT_DIR', './output')
    ALLOWED_EXTENSIONS = {'pdf'}
    #ALLOWED_EXTENSIONS = {'pdf', 'txt', 'doc', 'docx'}
    MAX_CONTENT_LENGTH = 16 * 1024 * 1024  # 16MB
    
    # RAGFlow配置
    RAGFLOW_CONFIG = {
        'address': os.getenv('RAGFLOW_ADDRESS', '192.168.184.227'),
        'protocol': os.getenv('RAGFLOW_PROTOCOL', 'http'),  # 添加协议配置，默认为http
        'api_key': os.getenv('RAGFLOW_API_KEY', 'ragflow-I2NWIzYzE0MDk0ODExZjA4Nzk4Y2U2MD'),
        'headers': {
            'Content-Type': 'application/json'
        }}
    
    # 数据库配置
    # 开发环境
    DATABASE_CONFIG = {
        'host': os.getenv('DB_HOST', '192.168.184.64'),
        'user': os.getenv('DB_USER', 'root'),
        'password': os.getenv('DB_PASSWORD', 'Aa_123qwe'),
        'database': os.getenv('DB_NAME', 'smart_water'),
        'pool_size': int(os.getenv('DB_POOL_SIZE', '10'))
    }
    # # 生产环境
    # DATABASE_CONFIG = {
    #     'host': os.getenv('DB_HOST', '192.168.183.123'),
    #     'user': os.getenv('DB_USER', 'root'),
    #     'password': os.getenv('DB_PASSWORD', '123qwe!@#'),
    #     'database': os.getenv('DB_NAME', 'smart_water'),
    #     'pool_size': int(os.getenv('DB_POOL_SIZE', '10'))
    # }
    # MinIO配置
    MINIO_CONFIG = {
        'endpoint': os.getenv('MINIO_ENDPOINT', '192.168.183.115:9000'),
        'access_key': os.getenv('MINIO_ACCESS_KEY', 'minioadmin'),
        'secret_key': os.getenv('MINIO_SECRET_KEY', 'minioadmin'),
        'secure': os.getenv('MINIO_SECURE', 'False').lower() == 'true',
        'bucket_name': os.getenv('MINIO_BUCKET', '20def7942674282277c3714ed7ea6ce0'),
        'secure':False 
    }
    
    
    # API配置
    API_CONFIG = {
        'upload_url': os.getenv('UPLOAD_URL', 'https://smart.swj.beijing.gov.cn/smartwaterdev/api/knowledge/uploadImage'),
        'image_address_url': os.getenv('IMAGE_ADDRESS_URL', 'https://smart.swj.beijing.gov.cn/smartwaterdev/api/knowledge/downloadByFileName')
    }
    
    # LLM模型配置
    LLM_CONFIGS = {
        'chat': {
            'model_type': 'chat',
            'llm_name': 'qwen25-72b',
            'api_base': 'http://192.168.184.157:8010/v1',
            'max_tokens': 64000,
            'llm_factory': 'OpenAI-API-Compatible',
            'api_key': 'sk-5XvbIRBE3dtc5MVH374e4dF7Cf6a4f6cAa219e03E28c883b'
        },
        'rerank': {
            'model_type': 'rerank',
            'llm_name': 'bge-reranker-base',
            'api_base': 'http://192.168.180.74:18000/v1',
            'max_tokens': 512,
            'llm_factory': 'Xinference'
        },
        'embedding': {
            'model_type': 'embedding',
            'llm_name': 'custom-embedding',
            'api_base': 'http://192.168.180.74:18000/v1',
            'max_tokens': 512,
            'llm_factory': 'Xinference'
        }
    }

    @classmethod
    def validate_llm_config(cls, config: dict) -> bool:
        """验证LLM配置是否有效"""
        required_fields = {
            'chat': ['llm_name', 'api_key'],
            'embedding': ['llm_name', 'api_key'],
            'rerank': ['llm_name', 'api_key']
        }
        
        if not isinstance(config, dict):
            return False
            
        for model_type, fields in required_fields.items():
            if model_type in config:
                model_config = config[model_type]
                if not isinstance(model_config, dict):
                    return False
                for field in fields:
                    if field not in model_config or not model_config[field]:
                        return False
        return True
    
    @classmethod
    def get_ragflow_headers(cls) -> Dict[str, str]:
        """获取RAGFlow请求头"""
        return {
            'Authorization': f'Bearer {cls.RAGFLOW_CONFIG["api_key"]}',
            **cls.RAGFLOW_CONFIG['headers']
        }
    
    @classmethod
    def get_tenant_info(cls, user_id: str, ragflow_user_id: str) -> Dict[str, Any]:
        """获取租户信息配置"""
        return {
            "tenant_id": ragflow_user_id,
            "name": user_id,
            "llm_id": f"{cls.LLM_CONFIGS['chat']['llm_name']}___OpenAI-API@OpenAI-API-Compatible",
            "embd_id": f"{cls.LLM_CONFIGS['embedding']['llm_name']}@Xinference",
            "img2txt_id": "",
            "asr_id": "",
            "rerank_id": f"{cls.LLM_CONFIGS['rerank']['llm_name']}@Xinference",
            "tts_id": None
        }
    
    @classmethod
    def get_dataset_config(cls) -> Dict[str, Any]:
        """获取数据集配置"""
        return {
            "name": "个人知识库",
            "language": "Chinese",
            "parser_config": {"chunk_token_num": 1024}
        } 